package com.sumer.psychology.common.persistence.mongodb;

import com.mongodb.BasicDBObject;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;

/**
 * 监听查看
 * <p/>
 * User: zhenguang.zhu
 * Date: 2014/10/30
 * Time: 11:15
 */
@Aspect
public class MongoViewProcessor extends AbstractMongoRepository {
    @Override
    protected String dbName() {
        return null;
    }

    /**
     * 再没有aop的环境下主动注册
     *
     * @param target           target
     * @param id               id
     * @param mongoApplication mongoApplication
     */
    public static void register(Object target, String id, MongoApplication mongoApplication) {
        MongoViewProcessor mongoViewProcessor = new MongoViewProcessor();
        mongoViewProcessor.setMongoApplication(mongoApplication);
        mongoViewProcessor.listen(target, id);
    }

    /**
     * 监听find by id请求
     *
     * @param target target
     * @param id     id
     */
    @After(value = "execution(* com.sumer.psychology.common.persistence.mongodb.AbstractMongoRepository.findById(..)) " +
            "&& target(target) && args(id)", argNames = "target,id")
    public void listen(Object target, String id) {
        AbstractMongoRepository mongoRepository = (AbstractMongoRepository) target;

        if (StringUtils.isNotBlank(mongoRepository.dbName())) {
            db().getCollection(mongoRepository.dbName()).update(
                    new BasicDBObject("_id", id),
                    new BasicDBObject("$inc", new BasicDBObject("views", 1)));
        }
    }

}
